const querystring = require('querystring')
const { set, get } = require("./src/db/redis")
const { access } = require("./src/utils/log")
const { handleUserRouter } = require("./src/router/user")
const { handleBlogRouter } = require("./src/router/blog")

// 这是获取过期时间
const getExpires = () => {
  const d = new Date()
  d.setTime(d.getTime() + 7 * 60 * 60 * 24 * 1000)
  return d.toGMTString()
}

// session数据
// const SESSION_DATA = {}

const getPostData = (req) => {
  const promise = new Promise((resolve, reject) => {
    if (req.method !== "POST") {
      resolve({})
      return
    }
    if (req.headers['content-type'] !== "application/json") {
      resolve({})
      return
    }
    let postData = ''

    // chunk 为16进制数据
    req.on("data", chunk => {
      postData += chunk.toString()
    })
    req.on("end", () => {
      if (!postData) {
        resolve({})
        return
      }
      resolve(
        JSON.parse(postData)
      )
    })
  })
  return promise
}
const serverHandle = (req, res) => {

  // 记录 access log
  access(`${req.method} -- ${req.url} -- ${req.headers['user-agent']} -- ${Date.now()}`)

  // 设置返回头
  res.setHeader("Content-type", "application/json")

  // 返回path
  const url = req.url
  const path = url.split("?")[0]

  // 解析query
  req.query = querystring.parse(url.split("?")[1])

  // 解析cookie
  const cookieStr = req.headers.cookie || ''
  req.cookie = {}
  cookieStr.split(";").forEach(item => {
    if (!item) {
      return
    }
    const arr = item.split("=")
    const key = arr[0]
    const value = arr[1]
    req.cookie[key] = value
  });

  // 解析session
  // let userId = req.cookie.userid
  // let needSetCookie = false
  // if(userId) {
  //   if(!SESSION_DATA[userId]){
  //     SESSION_DATA[userId] = {}
  //   }
  // } else {
  //   userId = Math.random().toString().slice(2,6)
  //   needSetCookie = true
  //   SESSION_DATA[userId] = {}
  // }
  // req.session = SESSION_DATA[userId]

  // 解析session （使用redis）
  let userId = req.cookie.userid
  let needSetCookie = false
  if (!userId) {
    needSetCookie = true
    userId = Math.random().toString(16).slice(2, 8)
    set(userId, {})
  }
  
  req.sessionId = userId

  get(userId).then(resolve => {
    if (resolve == null) {
      set(req.sessionId, {})
      req.session = {}
    } else {
      req.session = resolve
    }

    // 处理 post 请求
    return getPostData(req)
  }).then(postData => {
    req.body = postData
    // 处理博客路由
    const blogData = handleBlogRouter(req, res)

    // 此时的 blogData 是经过 SuccessModel 的 promise
    if (blogData) {
      blogData.then((blogData) => {
        if (needSetCookie) {
          res.setHeader("Set-Cookie", `userid=${userId};path=/;httpOnly;expires=${getExpires()}`)
        }
        res.end(
          JSON.stringify(blogData)
        )
      })
      return
    }

    // 处理登录路由
    const userData = handleUserRouter(req, res)
    if (userData) {
      userData.then(result => {
          if (needSetCookie) {
            res.setHeader("Set-Cookie", `userid=${userId};path=/;httpOnly;expires=${getExpires()}`)
          }
          res.end(
            JSON.stringify(result)
          )
      })
      return
    }

    // 如果所有路由未命中返回错误信息
    res.writeHeader(404)
    res.write("404 no found")
    res.end()
  })
}

module.exports = {
  serverHandle
}
